<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div style="width: 100%; display: flex; flex-direction: column; height: 100vh;">
    <div style="display: flex; align-items: center; padding: 1px 15px; position: relative;">
      <!-- 左侧新建按钮 -->
      <el-button class="idoo-details-add" >新增</el-button>
      <!-- 右侧信息区域：垂直展示 -->
      <div style="display: flex; flex-direction: column; margin-left: 10px;">
        <span style="font-size: 15px;"> <el-button type="primary" link @click="handleBack">题库</el-button></span>
        <div style="display: flex; align-items: center; font-size: 14px; margin-top: 4px;">
          <span class="sub-title">{{ detailsTitle }}</span>
          <el-tooltip content="保存" placement="top" v-if="isFormChanged">
            <el-icon class="hover-icon" style="margin-left: 10px;" @click="handleSave">
              <UploadFilled />
            </el-icon>
          </el-tooltip>
        </div>
      </div>
    </div>

    <!-- 带阴影的分割线 -->
    <div class="divider"></div>
    <!-- 后续内容区域：背景色为淡灰色，填满剩余区域 -->
    <div class="content-section">
      <div style="display: flex; width: 100%;">

        <!-- 左侧：无阴影的Card，占整体宽度的65%，用于表单的详情数据 -->
        <div style="height: auto; width: 65%; overflow-y: auto; margin-right: 10px;">
          <el-card style="box-shadow: none;">
            <el-form :model="examinaionBanckForm" style="width: 100%;">
              <el-form-item label="">
                <el-input v-model="examinaionBanckForm.name"
                  style="font-size: 30px; height: 60px; line-height: 60px; width: 70%; padding: 10px;"
                  class="idoo-details-input" placeholder="题库名称：XXXX-XX-XX 数学选择题题库"></el-input>
              </el-form-item>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="说明">
                    <el-input type="textarea" v-model="examinaionBanckForm.description" class="idoo-details-input"
                      placeholder="说明"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                </el-col>
              </el-row>
            </el-form>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { UploadFilled} from '@element-plus/icons-vue';
import router from '@/router';
import { ElMessageBox } from 'element-plus';
import { _getExaminaionBankInfo, _modifyExaminaionBankInfo, _saveExaminaionBankInfo } from '@/api/generic/examinaion/examinaion-bank-api';
import { getChangedFields, updateWrapperBuilder } from '@/utils/form/updateFormHelper';
import type { ExaminaionBankForm } from '@/types/examinaion/types';

const route = useRoute();
const detailsTitle = ref("");
const isFormChanged = ref(false);
let formId = route.query.id || "";
//是否打开业务选择器
const showDialog = ref(false);

// 初始化表单数据
const examinaionBanckForm = ref<ExaminaionBankForm>({
  /** 题库名称*/
  name: '',
  /** 题库描述*/
  description: '',
})
const originalFormData = ref<ExaminaionBankForm>({});
originalFormData.value = JSON.parse(JSON.stringify(examinaionBanckForm.value));

const resetForm = () => {
  originalFormData.value = JSON.parse(JSON.stringify(examinaionBanckForm.value));
  detailsTitle.value = examinaionBanckForm.value.name || '新建';
  isFormChanged.value = false;
}

// 监听表单变化
watch(() => examinaionBanckForm.value, (newVal) => {
  console.log(examinaionBanckForm.value);
  console.log(originalFormData.value)
  isFormChanged.value = JSON.stringify(newVal) !== JSON.stringify(originalFormData.value);
}, { deep: true });

//初始化加载数据
onMounted(async () => {
  detailsTitle.value = '新建'
  console.error(showDialog.value)
  //获取用户数据
  if (formId) {
    //查询题库信息
    //编辑
    const res = await _getExaminaionBankInfo({ id: formId.toString() });
    if (res.code === 200 && res.data) {
      examinaionBanckForm.value = res.data;
      originalFormData.value = JSON.parse(JSON.stringify(res.data));
      detailsTitle.value = examinaionBanckForm.value.name || '';
    }
  }
  console.log("onMounted", examinaionBanckForm.value)
});
//返回按钮
const handleBack = () => {
  if (isFormChanged.value) {
    ElMessageBox.confirm('是否保存当前数据？', '确认保存', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      await handleSave();
    }).catch(() => {
      router.push({ path: route.fullPath.replace('/add', '') })
    })
  } else {
    router.push({ path: route.fullPath.replace('/add', '') })
  }
}
// 保存处理函数
const handleSave = async () => {
  //TODO 表单校验
  const formData = examinaionBanckForm.value
  try {
    const i = getChangedFields(originalFormData.value, formData)
    let res;
    if (formId) {
      const upWrap = updateWrapperBuilder(formData, i); // 传递 formData 作为参数
      res = await _modifyExaminaionBankInfo(upWrap); // 使用 upWrap 作为参数
    } else {
      res = await _saveExaminaionBankInfo(formData);
      if (res.code === 200 && res.data) {
        formId = res.data[0];
        examinaionBanckForm.value.id = formId;
      }
    }
    if (res && res.code === 200) {
      resetForm();
    }
  } catch (error) {
    console.error('保存失败:', error);
  }
};




</script>
<style scoped>
:deep(.el-input__inner) {
  --el-input-inner-height: none;
}

:deep(.el-card__body) {
  padding: 1% !important;
  justify-content: unset !important;
}

.hover-icon {
  cursor: pointer;
  transition: transform 0.2s ease;
}

.hover-icon:hover {
  transform: translateY(-2px);
}

.sub-title {
  font-size: 14px;
  color: #666;
}

.divider {
  width: 100%;
  height: 1px;
  background-color: #ccc;
  margin-top: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.content-section {
  flex: 1;
  width: 100%;
  padding: 15px;
  background-color: #f5f5f5;
  box-sizing: border-box;
}

.demo-tabs>.el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.demo-tabs {
  position: relative;
  width: 100%;
}

:deep(.el-tabs__nav-wrap::after) {
  position: absolute;
  content: '';
  width: 100%;
  height: 2px;
  background-color: var(--el-border-color-light);
  bottom: 0;
  left: 0;
  z-index: 1;
}

:deep(.el-tabs__nav.is-top) {
  margin-left: 10px
}

:deep(.el-tabs__header) {
  width: 100%;
  margin-bottom: 0;
}

:deep(.el-tabs__nav-wrap) {
  width: 100%;
}
</style>
